package com.onion.mvc.resolver.builder;

import com.onion.mvc.annotation.OnionParam;
import com.onion.mvc.enums.ParamPolicy;
import com.onion.utils.surface.request.Request;
import com.onion.utils.surface.request.RequestHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;

public class ParamPriorParamBuilder implements RequestParamBuilder {

    @Override
    public ParamPolicy mode() {
        return ParamPolicy.PARAM_PRIOR;
    }

    @Override
    public Request build(NativeWebRequest webRequest, MethodParameter parameter) {
        if(RequestHelper.isBasicType(parameter.getParameterType())){
            OnionParam onionParam = parameter.getParameterAnnotation(OnionParam.class);
            String paramName = onionParam!=null ? onionParam.name() : null;
            if(StringUtils.isBlank(paramName)){
                paramName = parameter.getParameterName();
            }
            return RequestHelper.buildBasicRequest(webRequest.getParameter(paramName), parameter.getParameterType());
        }else{
            return null;
        }
    }

}